package redpack

import (
    "fmt"
	"crypto/tls"
	"wxsdk/wxpay/core"
	. "wxsdk/wxpay"
)

// 发放普通红包
type NormalRedPackReq struct {
	NonceStr     string   `xml:"nonce_str"`                //随机字符串，不长于32位
	Sign         string   `xml:"sign"`                     //签名
	MchBillno    string   `xml:"mch_billno"`               //商户订单号
	MchId        string   `xml:"mch_id"`                   //微信支付分配的商户号
    SubMchId     string   `xml:"sub_mch_id,omitempty"`     //微信支付分配的子商户号,服务商模式下必填***
	Wxappid      string   `xml:"wxappid"`                  //公众账号appid
	Msgappid     string   `xml:"msgappid,omitempty"`       //子商户appid,服务商模式下必填***
	SendName     string   `xml:"send_name"`                //红包发送者名称
	ReOpenid     string   `xml:"re_openid"`                //接受红包的用户
	TotalAmount  string   `xml:"total_amount"`             //付款金额，单位分
	TotalNum     string   `xml:"total_num"`                //红包发放总人数
	Wishing      string   `xml:"wishing"`                  //红包祝福语
	ClientIp     string   `xml:"client_ip"`                //调用接口的机器Ip地址
	ActName      string   `xml:"act_name"`                 //活动名称
	Remark       string   `xml:"remark"`                   //备注信息
	SceneId      string   `xml:"scene_id,omitempty"`       //发放红包使用场景，红包金额大于200时必传
	RiskInfo     string   `xml:"risk_info,omitempty"`      //活动信息
	ConsumeMchId string   `xml:"consume_mch_id,omitempty"` //资金授权商户号
}

type NormalRedPackRsp struct {
	BaseResponse         `xml:",innerXml,omitempty"`
	WxAppId       string `xml:"wxappid"`       // 商户appid
	MchBillno     string `xml:"mch_billno"`    // 商户订单号
	ReOpenid      string `xml:"re_openid"`     // 用户openid
	TotalAmount   string `xml:"total_amount"`  // 付款金额，单位分
	SendListid    string `xml:"send_listid"`   // 红包订单的微信单号
}

func NormalRedPack(appId,msgappid,mchId,subMchId,appSecret,orderId,openId,sendName,amountStr,totalNum,
                   clientIp,wishing,actName,remark,sceneId,crt,key string) (NormalRedPackRsp,error){
	var (
	    req = new(NormalRedPackReq)
	    rsp NormalRedPackRsp
	)
	cert, err := tls.X509KeyPair([]byte(crt), []byte(key))
	if err != nil {
		return rsp, err
	}
	tlsConfig := &tls.Config{
		Certificates: []tls.Certificate{cert},
	}
	client := core.GetWxCoPayClient(appSecret,tlsConfig)
	//
	req.Wxappid = appId
	req.Msgappid = msgappid
	req.MchId = mchId
	req.SubMchId = subMchId
	req.MchBillno = orderId
	req.ReOpenid = openId
	req.SendName = sendName
	req.TotalAmount = amountStr      // 单位是分
	req.TotalNum = totalNum    
	req.ClientIp = clientIp
	req.Wishing = wishing
	req.ActName = actName
	req.Remark = remark
	req.SceneId = sceneId
	serverUrl := fmt.Sprintf("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack")
	err = client.Excute(serverUrl, req, &rsp, true)
    if err != nil {
		return rsp, err
	}
	return rsp, nil
}
